<template>
<div  :style="{ height: containerMinHeight}" id="table-full-screen" >
  <!-- 搜索栏 -->
  <ArtSearchBar
	v-model:filter="formFilters"
	:items="formItems"
	:showExpand="false"
	@reset="handleReset"
	@search="handleSearch"
  ></ArtSearchBar>

  <ElCard shadow="never" class="art-table-card" style="height: calc(100vh - 214px);">
	<!-- 表格头部 -->
	<ArtTableHeader v-model:columns="columnChecks" @refresh="handleRefresh">
	  <template #left>
		<ElButton @click="showDialog('add')">新建数据源</ElButton>
	  </template>
	</ArtTableHeader>

	<div style="height: calc(100% - 35px);">
		<ArtTable
		  ref="tableRef"
		  row-key="id"
		  :loading="loading"
		  :data="tableData"
		  :height="'100%'"
		>
		  <template #default>
			<ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
		  </template>
		</ArtTable>
	</div>

	<ElDialog
	  v-model="dialogVisible"
	  :title="dialogType === 'add' ? '添加数据源' : '编辑数据源'"
	  width="30%"
	  align-center
	  :close-on-click-modal="false"
	  :draggable="true"
	>
	  <ElForm ref="formRef" :model="formData" :rules="rules" label-width="120px">
		<ElFormItem label="数据库名称" prop="name">
		  <ElInput v-model="formData.name" />
		</ElFormItem>
		<ElFormItem label="数据库类型" prop="type">
		  <ElSelect v-model="formData.type">
			<ElOption label="MySQL" value="mysql" />
			<ElOption label="PostgreSQL" value="postgresql" />
			<ElOption label="SQLServer" value="sqlserver" />
			<ElOption label="Oracle" value="oracle" />
			<ElOption label="SQLite" value="sqlite" />
		  </ElSelect>
		</ElFormItem>
		<ElFormItem label="连接地址" prop="url">
		  <ElInput v-model="formData.url" />
		</ElFormItem>
		<ElFormItem label="驱动程序类" prop="driver">
		  <ElInput v-model="formData.driver" />
		</ElFormItem>
		<ElFormItem label="数据库用户名" prop="username">
		  <ElInput v-model="formData.username" />
		</ElFormItem>
		<ElFormItem label="数据库密码" prop="password">
		  <ElInput v-model="formData.password" />
		</ElFormItem>
		<ElFormItem label="初始连接数" prop="initialSize">
		  <ElInput v-model="formData.initialSize" />
		</ElFormItem>
		<ElFormItem label="最小连接池数量" prop="minimumIdle">
		  <ElInput v-model="formData.minimumIdle" />
		</ElFormItem>
		<ElFormItem label="最大连接池数量" prop="maximumActiveSize">
		  <ElInput v-model="formData.maximumActiveSize" />
		</ElFormItem>
		<ElFormItem label="连接超时时间" prop="connTimeout">
		  <ElInput v-model="formData.connTimeout" />
		</ElFormItem>
		<ElFormItem label="空闲检测时间" prop="idleTimeout">
		  <ElInput v-model="formData.idleTimeout" />
		</ElFormItem>
		<ElFormItem label="空闲检测语句" prop="connTestQuery">
		  <ElInput v-model="formData.connTestQuery" />
		</ElFormItem>
		<ElFormItem label="输出Sql" prop="showSql">
		  <ElSelect v-model="formData.showSql">
			<ElOption label="输出" value="1" />
			<ElOption label="禁止" value="0" />
		  </ElSelect>
		</ElFormItem>
		<ElFormItem label="启动类型" prop="startupType">
		  <ElSelect v-model="formData.startupType">
			<ElOption label="手动" value="1" />
			<ElOption label="自动" value="0" />
			<ElOption label="禁用" value="-1" />
		  </ElSelect>
		</ElFormItem>
	  </ElForm>
	  <template #footer>
		<div class="dialog-footer">
		  <ElButton @click="dialogVisible = false">取消</ElButton>
		  <ElButton type="primary" @click="handleSubmit">提交</ElButton>
		</div>
	  </template>
	</ElDialog>
  </ElCard>
</div>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { ElDialog, FormInstance, ElTag } from 'element-plus'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import type { FormRules } from 'element-plus'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
  import { DbConfigService } from '@/api/data-rule/dbApi'
  import { SearchChangeParams, SearchFormItem } from '@/types'
  import dayjs from 'dayjs';
  import { useCommon } from '@/composables/useCommon'
  const { containerMinHeight } = useCommon()
  const { width } = useWindowSize()
  defineOptions({ name: 'DataSource' }) // 定义组件名称，用于 KeepAlive 缓存控制

  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const loading = ref(false)

  // 定义表单搜索初始值
  const initialSearchState = {
    name: '',
    type: '',
    username: '',
    password: '',
    url: '',
    initialSize: 5,
    minimumIdle: 10,
    maximumActiveSize: 20,
	connTimeout: 60000,
	idleTimeout: 60000,
	connTestQuery: '',
	showSql: '0',
	startupType: '-1',
  }

  // 响应式表单数据
  const formFilters = reactive({ ...initialSearchState })

  const pagination = reactive({
    currentPage: 1,
    pageSize: 20,
    total: 0
  })

  // 表格数据
  const tableData = ref<any[]>([])

  // 表格实例引用
  const tableRef = ref()

  // 选中的行数据
  const selectedRows = ref<any[]>([])

  // 重置表单
  const handleReset = () => {
    Object.assign(formFilters, { ...initialSearchState })
    pagination.currentPage = 1 // 重置到第一页
    getDataSourceList()
  }

  // 搜索处理
  const handleSearch = () => {
    console.log('搜索参数:', formFilters)
    pagination.currentPage = 1 // 搜索时重置到第一页
    getDataSourceList()
  }

  // 表单项变更处理
  const handleFormChange = (params: SearchChangeParams): void => {
    console.log('表单项变更:', params)
  }

  // 表单配置项
  const formItems: SearchFormItem[] = [
    {
      label: '数据源',
      prop: 'name',
      type: 'input',
      config: {
        clearable: true
      },
      onChange: handleFormChange
    },
  ]

  // 获取标签类型
  // 1: 在线 2: 离线 3: 异常
  const getTagType = (status: string) => {
    switch (status) {
      case '1':
        return 'success'
      case '2':
        return 'info'
      case '3':
        return 'warning'
      case '4':
        return 'danger'
      default:
        return 'info'
    }
  }

  // 构建标签文本
  const buildTagText = (status: string) => {
    let text = ''
    if (status === '1') {
      text = '在线'
    } else if (status === '2') {
      text = '离线'
    } else if (status === '3') {
      text = '异常'
    } else{
      text = '未知'
    }
    return text
  }

  // 显示对话框
  const showDialog = (type: string, row?: any) => {
    dialogVisible.value = true
    dialogType.value = type

    // 重置表单验证状态
    if (formRef.value) {
      formRef.value.resetFields()
    }

    if (type === 'edit' && row) {
	  formData.id=row.id;
	  formData.name=row.name;
	  formData.type= row.type;
	  formData.username=row.username;
	  formData.password=row.password;
	  formData.url=row.url;
	  formData.initialSize=row.initialSize;
	  formData.minimumIdle=row.minimumIdle;
	  formData.maximumActiveSize=row.maximumActiveSize;
	  formData.connTimeout=row.connTimeout;
	  formData.idleTimeout=row.idleTimeout;
	  formData.connTestQuery=row.connTestQuery;
	  formData.showSql= row.showSql;
	  formData.startupType=row.startupType;
	  formData.driver=row.driver;
    } else {
	  formData.id='';
	  formData.name='';
	  formData.type= '';
	  formData.username='';
	  formData.password='';
	  formData.url='';
	  formData.initialSize=5;
	  formData.minimumIdle=10;
	  formData.maximumActiveSize=20;
	  formData.connTimeout=60000;
	  formData.idleTimeout=60000;
	  formData.connTestQuery='';
	  formData.showSql= '0';
	  formData.startupType='-1';
    }
  }

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
	{ prop: 'name', label: '数据库名称' },
	{ prop: 'type', label: '数据库类型' },
	{ prop: 'initialSize', label: '初始连接数' },
	{ prop: 'maximumActiveSize', label: '最大连接池数量' },
    {
      prop: 'status',
      label: '状态',
	  formatter: (row: any) => {
	  		return h(ElTag, { type: row.status === '0' ? 'success' : 'info' }, () => {
	  		   return row.status === '0' ? '正在运行' : '已停止'
	  		})
	  }
    },
	{
	  prop: 'startupType',
	  label: '启动类型',
	  sortable: false,
	  formatter: (row:any) => {
		  if(row.startupType==0){
			  return "自动";
		  }
		  else if(row.startupType==1){
			  return "手动";
		  }else{
			  return "禁用";
		  }
	  }
	},
    {
      prop: 'createTime',
      label: '创建日期',
      sortable: true,
	  formatter: (row:any) => {
			return dayjs(row.modifyTime).format('YYYY-MM-DD HH:MM:ss')
	  }
    },
    {
      prop: 'operation',
      label: '操作',
      width: 250,
      fixed: 'right', // 固定在右侧
      formatter: (row: any) => {
        return h('div', [
          h(ArtButtonTable, {
            type: 'edit',
			tip:true,
			tipContent:'编辑',
            onClick: () => showDialog('edit', row)
          }),
		  row.status=='1' && 
		  h(ArtButtonTable, {
			icon:'&#xe6e8;',
			iconColor:'#67c23a',
			tip:true,
			tipContent:'启动',
		    onClick: () => startDbConfig(row)
		  }),
		  row.status=='0' &&
		  h(ArtButtonTable, {
			icon:'&#xe780;',
			iconColor:'#f56c6c',
			tip:true,
			tipContent:'停止',
		    onClick: () => stopDbConfig(row)
		  }),
		  h(ArtButtonTable, {
			icon:'&#xe878;',
			iconColor:'#e6a23c',
			tip:true,
			tipContent:'检测连接',
		    onClick: () => checkDbConfig(row)
		  }),
          h(ArtButtonTable, {
            type: 'delete',
			tip:true,
			tipContent:'删除',
            onClick: () => deleteDbConfig(row)
          })
        ])
      }
    }
  ])

  // 表单实例 
  const formRef = ref<FormInstance>()

  // 表单数据
  const formData = reactive({
	id:'',
    name: '',
    type: '',
    username: '',
    password: '',
    url: '',
    initialSize: 5,
    minimumIdle: 10,
    maximumActiveSize: 20,
	connTimeout: 60000,
	idleTimeout: 60000,
	connTestQuery: '',
	showSql: '0',
	startupType: '-1',
	driver:''
  })

  onMounted(() => {
    getDataSourceList()
  })

  const getDataSourceList = async () => {
    loading.value = true
    try {
	  const data = await DbConfigService.getAll({
		query:formFilters
	  })
      tableData.value = data
    } catch (error) {
      console.error('获取数据源列表失败:', error)
    } finally {
      loading.value = false
    }
  }

  const handleRefresh = () => {
    getDataSourceList()
  }

  // 处理表格行选择变化
  const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection
  }

  // 表单验证规则
  const rules = reactive<FormRules>({
	name: [
		{ required: true, message: '请输入数据库名称', trigger: 'blur' },
		{ min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
	],
	type: [
	  { required: true, message: '请输入数据库类型', trigger: 'blur' },
	],
    username: [
      { required: true, message: '请输入数据库用户名', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
	password: [
	  { required: true, message: '请输入数据库密码', trigger: 'blur' },
	],
	url: [
	  { required: true, message: '请输入数据库连接地址', trigger: 'blur' },
	],
	initialSize: [
	  { required: true, message: '请输入数据库初始连接数', trigger: 'blur' },
	],
	minimumIdle: [
	  { required: true, message: '请输入数据库最小连接池数', trigger: 'blur' },
	],
	maximumActiveSize: [
	  { required: true, message: '请输入数据库最大连接池数量', trigger: 'blur' },
	],
	connTimeout: [
	  { required: true, message: '请输入数据库连接超时时间', trigger: 'blur' },
	],
	idleTimeout: [
	  { required: true, message: '请输入数据库连接空闲检测时间', trigger: 'blur' },
	],
	connTestQuery: [
	  { required: true, message: '请输入数据库连接空闲检测语句', trigger: 'blur' },
	],
	showSql: [
	  { required: true, message: '请选择是否输出执行Sql语句', trigger: 'blur' },
	],
	startupType: [
	  { required: true, message: '请选择启动类型', trigger: 'blur' },
	]
  })

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
      if (valid) {
		loading.value = true
        try {
  			await DbConfigService.save(formData);
			const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
			ElMessage.success(message)
  			getDataSourceList();
        } catch {
  			ElMessage.error(`失败`)
        }finally{
			loading.value = false;
			dialogVisible.value = false
		}
      }
    })
  }
  
  const deleteDbConfig =  (row:any) => {
    ElMessageBox.confirm('确定删除该【'+row.name+'】吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(async () => {
  		loading.value = true
  		try {
  			await DbConfigService.delete(row.id);
  			ElMessage.success('删除成功')
  			getDataSourceList();
  		}finally{
			loading.value = false
  		}
    })
  }
  
  const checkDbConfig =  (row:any) => {
    ElMessageBox.confirm('确定检测【'+row.name+'】数据源是否正确吗？', '配置检测', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
  		loading.value = true
  		try {
  			await DbConfigService.check(row.id);
  			ElMessage.success('成功')
  		}finally{
  			loading.value = false
  		}
    })
  }
  
  const stopDbConfig =  (row:any) => {
    ElMessageBox.confirm('确定停止【'+row.name+'】数据源吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
  		loading.value = true
  		try {
  			await DbConfigService.stop(row.id);
  			ElMessage.success('成功')
			getDataSourceList()
  		}finally{
  			loading.value = false
  		}
    })
  }
  
  const startDbConfig =  (row:any) => {
    ElMessageBox.confirm('确定启动【'+row.name+'】数据源吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
  		loading.value = true
  		try {
  			await DbConfigService.start(row.id);
  			ElMessage.success('成功')
			getDataSourceList()
  		}finally{
  			loading.value = false
  		}
    })
  }
  
  
  // 处理表格分页变化
  const handleSizeChange = (newPageSize: number) => {
    pagination.pageSize = newPageSize
    getDataSourceList()
  }

  const handleCurrentChange = (newCurrentPage: number) => {
    pagination.currentPage = newCurrentPage
    getDataSourceList()
  }
</script>

<style lang="scss" scoped>
  .account-page {
    :deep(.user) {
      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 6px;
      }

      > div {
        margin-left: 10px;

        .user-name {
          font-weight: 500;
          color: var(--art-text-gray-800);
        }
      }
    }
  }
</style>
